package com.xf.zk.curator.example.znode;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;
import org.apache.curator.utils.ZKPaths.PathAndNode;
import org.apache.zookeeper.ZooKeeper;

public class ZKPath {
	static String path = "/curator_zkPath";
	// 创建CuratorFramework 客户端实例，集群服务器地址为127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183，session timeout5000ms
	// 回调策略为ExponentialBackoffRetry，即为retries 3 times with increasing 1000 sleep time between retries
	static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183")
			.sessionTimeoutMs(5000).retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();

	public static void main(String[] args) throws Exception {
		// 开始连接
		client.start();
		// 获取原生zookeeper
		ZooKeeper zookeeper = client.getZookeeperClient().getZooKeeper();
		// 修改namespace为/curator_zkPath，节点路径为sub
		System.out.println(org.apache.curator.utils.ZKPaths.fixForNamespace(path, "sub"));
		// 在父节点path下创建子节点sub
		System.out.println(org.apache.curator.utils.ZKPaths.makePath(path, "sub"));
		// 获取节点路径
		System.out.println(org.apache.curator.utils.ZKPaths.getNodeFromPath("/curator_zkPath/sub1"));
		// 获取path 和 node
		PathAndNode pn = org.apache.curator.utils.ZKPaths.getPathAndNode("/curator_zkPath/sub1");
		System.out.println(pn.getPath());
		System.out.println(pn.getNode());
		String dir1 = path + "/child1";
		String dir2 = path + "/child2";
		// 创建节点，没有数据
		org.apache.curator.utils.ZKPaths.mkdirs(zookeeper, dir1);
		org.apache.curator.utils.ZKPaths.mkdirs(zookeeper, dir2);
		// 获取子节点
		System.out.println(org.apache.curator.utils.ZKPaths.getSortedChildren(zookeeper, path));
		// 获取子节点，同时删除本身
		org.apache.curator.utils.ZKPaths.deleteChildren(client.getZookeeperClient().getZooKeeper(), path, true);
	}
}
